<?php

namespace App\Console\Commands\OpenShop;

use App\Library\Rms\RmsShopApi;
use App\Models\OpenShop\Common\ShopArchiveModel;
use App\Models\OpenShop\SiteLocation\OpenShopSiteLocationModel;
use Illuminate\Console\Command;
use Illuminate\Support\Str;

class ExportShopArchiveCommand extends Command
{
    protected $signature = 'export:shop-archive';

    protected $description = '导出门店的营业执照、食品、租赁合同';

    public function handle()
    {
        ini_set('memory_limit', '2048M');

        // 租赁合同
        OpenShopSiteLocationModel::query()->with('mainProcessRel')
                                 ->where('leaseFiles', '!=', '')
                                 ->select('orderNo', 'leaseFiles')->orderByDesc('id')->get()->map(function ($item) {

                if (!$item->mainProcessRel) {
                    dump(1);
                    return;
                }

                if (!$item->mainProcessRel->shopId) {
                    dump(2);
                    return;
                }

                if (isset( $this->shops[$item->mainProcessRel->shopId]['leaseFiles'])) {
                    dump(3);

                    return;
                }

                $files = json_decode($item->leaseFiles, true);
                foreach ($files as $file) {
                    if (!isset($file['url'])) {
                        continue;
                    }

                    $this->shops[$item->mainProcessRel->shopId]['leaseFiles'][] = sprintf($file['url'], 'https://file.51kuafu.com/');
                }

            });

        ShopArchiveModel::query()->with('resourcesRel')->orderByDesc('id')->chunk(500, function ($shopArchives) {
            $shopArchives->each(function ($shopArchive) {

                if (isset( $this->shops[$shopArchive->shopId]['yyzz'])) {
                    return;
                }

                if ($shopArchive->resourcesRel->count() == 0) {
                    return;
                }

                // 营业执照
                $shopArchive->resourcesRel->where('name', ShopArchiveModel::RESOURCE_BUSINESS_IMG)->pluck('url')->each(function ($url) use ($shopArchive) {
                    $this->shops[$shopArchive->shopId]['yyzz'][] = 'https://file.51kuafu.com/' . $url;
                });


                // 食品经营
                $shopArchive->resourcesRel->where('name', ShopArchiveModel::RESOURCE_FOOD_BUSINESS_IMG)->pluck('url')->each(function ($url) use ($shopArchive) {
                    $this->shops[$shopArchive->shopId]['spjy'][] = 'https://file.51kuafu.com/' . $url;
                });
            });
        });

        $shopIds = array_keys($this->shops);

        $shopInfo = collect((new RmsShopApi())->getShopByIds($shopIds, ['id', 'shopCode', 'name'])['data']['shopList'] ?? [])->keyBy('id');

        foreach ($this->shops as $shopId => &$shop) {
            $shop['shopCode'] = $shopInfo[$shopId]['shopCode'] ?? '';
            $shop['shopName'] = $shopInfo[$shopId]['name'] ?? '';
        }

        $this->shops = array_values($this->shops);
        $this->info('总行数：'.count($this->shops));

        // TODO DEBUG
//        $this->shops = array_slice($this->shops, 0, 10);

        // 写入文件

        // 1. 创建根文件夹
        $rootPath = sys_get_temp_dir() . '/' . Str::random().'/shopinfo';
        if (!is_dir($rootPath)) {
            mkdir($rootPath, 0777, true);
        }


        foreach ($this->shops as $k => $shop) {

            // 2. 创建门店文件夹
            $shopPath = $rootPath .'/'. $shop['shopCode']. '-'.$shop['shopName'];

            if (!is_dir($shopPath)) {
                mkdir($shopPath, 0777, true);
            }

            // 3. 写入营业执照
            if (isset($shop['yyzz'])) {
                foreach ($shop['yyzz'] as $key => $yyzz) {
                    $content = file_get_contents($yyzz);
                    file_put_contents($shopPath . '/营业执照' . $key . '.jpg', $content);
                }
            }

            // 4. 写入食品经营
            if (isset($shop['spjy'])) {
                foreach ($shop['spjy'] as $key => $spjy) {
                    $content = file_get_contents($spjy);
                    file_put_contents($shopPath . '/食品经营' . $key . '.jpg', $content);
                }
            }

            // 5. 写入租赁合同
            if (isset($shop['leaseFiles'])) {
                foreach ($shop['leaseFiles'] as $key => $leaseFile) {
                    $content = file_get_contents($leaseFile);
                    file_put_contents($shopPath . '/租赁合同' . $key . '.jpg', $content);
                }
            }

            $this->info($k.'-'.$shop['shopName'].'-'.$shop['shopCode']);
        }
        dump($rootPath);
    }
}
